package heven.holt.library.widget

import android.annotation.SuppressLint
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.content.ContextCompat
import heven.holt.library.R

/**
 * 封装带删除按钮的EditText
 */
class ClearEditText @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = android.R.attr.editTextStyle
) : AppCompatEditText(context, attrs, defStyleAttr), TextWatcher {
    private val clearDrawable =
        ContextCompat.getDrawable(context, R.drawable.selector_edit_text_delete)

    init {
        clearDrawable?.apply {
            setBounds(0, 0, intrinsicWidth, intrinsicHeight)
        }
        setClearIconVisible(false)
        addTextChangedListener(this)
    }

    private fun setClearIconVisible(visible: Boolean) {
        val right = if (visible) clearDrawable else null
        setCompoundDrawables(
            compoundDrawables[0],
            compoundDrawables[1],
            right,
            compoundDrawables[3]
        )
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_UP) {
            clearDrawable?.let {
                val xTouchable = (event.x > width - paddingRight - it.intrinsicWidth
                        && event.x < width - paddingRight)
                val yTouchable = (event.y > (height - it.intrinsicHeight) / 2
                        && event.y < (height + it.intrinsicHeight) / 2)
                if (xTouchable && yTouchable) {
                    setText("")
                }
            }
        }
        return super.onTouchEvent(event)
    }

    override fun onTextChanged(
        text: CharSequence?,
        start: Int,
        lengthBefore: Int,
        lengthAfter: Int
    ) {
        setClearIconVisible(!text.isNullOrEmpty())
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
    }

    override fun afterTextChanged(s: Editable?) {
    }
}